import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import { addCar } from "../../store/car/carActions";
import { useDispatch } from "react-redux";
interface ItemState {
  id: string;
  price: string | number;
  title: string;
  url: string;
}

const Index: React.FC = () => {
  const params = useParams();
  const id = params.id;
  const [item, setItem] = useState<ItemState>();
  const dispatch = useDispatch();

  const getDetailData = async () => {
    const resp = await axios.post("/api/detail", { id });
    const { code, data, message } = resp.data;
    if (code === 200) {
      setItem(data);
    } else {
    }
  };

  useEffect(() => {
    getDetailData();
  }, []);

  if (!item) {
    return <div>loading</div>;
  }

  return (
    <div>
      <img src={item.url} alt="" width={"100%"} />
      <h3>{item.title}</h3>
      <p>￥： {item.price}</p>
      <button
        onClick={() =>
          dispatch(
            addCar({
              ...item,
              count: 1,
              checked: false,
            })
          )
        }
      >
        加入购物车
      </button>
    </div>
  );
};

export default Index;
